package com.atguigu.juc.chap02;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class DeadlockDemo02 {

    private static final ReentrantLock lock01 = new ReentrantLock();
    private static final ReentrantLock lock02 = new ReentrantLock();

    public static void main(String[] args) {

        // 线程A
        new Thread(() -> {

            // 立即返回是否获取到锁
            boolean result01 = false;
            try {
                result01 = lock01.tryLock(1, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            if (result01) {
                System.out.println("A持有锁1，想要获取锁2");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                boolean result02 = false;
                try {
                    result02 = lock02.tryLock(1, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                if (result02) {
                    System.out.println("A持有锁1和锁2");

                    lock02.unlock();
                    System.out.println("A释放了锁2");
                }

                lock01.unlock();
                System.out.println("A释放了锁1");
            }
        }, "A").start();

        // 线程B
        new Thread(() -> {

            boolean result01 = lock02.tryLock();
            if (result01) {
                System.out.println("B持有锁2，想要获取锁1");

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }


                boolean result02 = lock01.tryLock();
                if (result02) {
                    System.out.println("B持有锁1和锁2");

                    lock01.unlock();
                    System.out.println("B释放了锁1");
                }

                lock02.unlock();
                System.out.println("B释放了锁2");
            }
        }, "B").start();
    }

}